using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Data.SqlClient;

public partial class WorkFlowRuleset : System.Web.UI.Page
{
    bool IsEdit = false;
    bool IsCopy = false;
    string[] cols = new string[] { "af_row_id", "RuleName", "SourceTitle", "Target", "TargetTitle", "AddWorkItem", "WI_Message", "addFieldUpdate", "FieldUpdateField", "FieldUpdateValue", "addFieldUpdateReject", "FieldUpdateFieldReject", "FieldUpdateValueReject", "addFieldEmail", "FieldEmailTemplate", "addFieldEmailRej", "FieldEmailTemplateRej" };//Added by John Sathish
    ArrayList arDef = null;
    DataSet dsWorkflow = new DataSet();
    HtmlForm frmObj;
    protected void Page_init(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                loadObjects();
                loadDefaultValues();
                loadTitle();
                Session["dtWorkflow"] = null;
            }
            arDef = getDefaultColumns();
            //loadRules();
        }
        catch (Exception Ex)
        {
            LogWriter.WriteLog("Page_init : Error : " + Ex.Message);
        }
    }

    protected void Page_PreLoad(object sender, EventArgs e)
    {
        if (IsPostBack)
            deleteRule_Click();
    }

    private void loadTitle()
    {
        try
        {
            HDDatabase HDD = new HDDatabase();
            DataTable dtTitle = HDD.GetDataTable("Select title as txt, title as val from sy_org_structure");

            string sTemp = "";
            foreach (DataRow drr in dtTitle.Select("", "txt asc"))
                sTemp += drr["txt"].ToString() + ",";
            DataRow dr = dtTitle.NewRow();
            dr["txt"] = "--Select a title--";
            dr["val"] = "";
            dtTitle.Rows.InsertAt(dr, 0);

            ddlSourceTitle.DataSource = dtTitle.DefaultView;
            ddlTargetTitle.DataSource = dtTitle.DefaultView;

            ddlSourceTitle.DataTextField = "txt";
            ddlTargetTitle.DataTextField = "txt";

            ddlSourceTitle.DataValueField = "val";
            ddlTargetTitle.DataValueField = "val";

            ddlSourceTitle.DataBind();
            ddlTargetTitle.DataBind();
            dr = null;
            dtTitle.Dispose();
            dtTitle = null;
            DataTable dtUser = HDD.GetDataTable("Select user_id as txt, user_id as val from sy_usr");
            dr = dtUser.NewRow();
            dr["txt"] = "--Select an user--";
            dr["val"] = "";
            dtUser.Rows.InsertAt(dr, 0);

            DataTable dtEmailTemplate = HDD.GetDataTable("Select name as txt, name as val from sy_email_template");
            dr = dtEmailTemplate.NewRow();
            dr["txt"] = "--Select Template--";
            dr["val"] = "";
            dtEmailTemplate.Rows.InsertAt(dr, 0);

            ddlSourceUser.DataSource = dtUser.DefaultView;
            ddlTargetUser.DataSource = dtUser.DefaultView;
            ddlAppEmail.DataSource = dtEmailTemplate.DefaultView;
            ddlRejEmail.DataSource = dtEmailTemplate.DefaultView;

            ddlSourceUser.DataTextField = "txt";
            ddlTargetUser.DataTextField = "txt";
            ddlAppEmail.DataTextField = "txt";
            ddlRejEmail.DataTextField = "txt";

            ddlSourceUser.DataValueField = "val";
            ddlTargetUser.DataValueField = "val";
            ddlAppEmail.DataValueField = "val";
            ddlRejEmail.DataValueField = "val";


            ddlSourceUser.DataBind();
            ddlTargetUser.DataBind();
            ddlAppEmail.DataBind();
            ddlRejEmail.DataBind();
            hf_Title.Value = sTemp;
            sTemp = "";// "<OPTION SELECTED>Select an user</OPTION>";
            foreach (DataRow drr in dtUser.Select("", "txt asc"))
                if (drr["txt"].ToString().ToLower() != "--select an user--")
                    sTemp += drr["txt"].ToString() + ",";//"<OPTION>" + drr["txt"].ToString() + "</OPTION>";
            hf_User.Value = sTemp;
            dr = null;
            dtUser.Dispose();
            dtUser = null;
            HDD = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("loadTitle : Error : " + ex.Message);
        }
    }

    private bool loadRules()
    {
        bool bRet = false;
        try
        {
            if (Session["dtWorkflow"] != null)
            {
                showRulesOnTable((DataTable)Session["dtWorkflow"]);
                bRet = true;
            }
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("loadRules : Error : " + ex.Message);
        }
        return bRet;
    }

    private void loadObjects()
    {
        try
        {
            ddObject.Items.Add(new ListItem("--None--", ""));
            ddField1.Items.Add(new ListItem("--None--", ""));
            ddField2.Items.Add(new ListItem("--None--", ""));
            ddField3.Items.Add(new ListItem("--None--", ""));
            ddField4.Items.Add(new ListItem("--None--", ""));
            ddField5.Items.Add(new ListItem("--None--", ""));
            //ddSkipField.Items.Add(new ListItem("--None--", ""));
            ddFieldsUpdate.Items.Add(new ListItem("--None--", ""));
            ddFieldsUpdateReject.Items.Add(new ListItem("--None--", ""));
            HDDatabase hdd = new HDDatabase();
            string sql = "select object_name, object_id,af_row_id from sy_obj order by object_name asc";
            sql = applysecurity(sql);
            DataSet ds = hdd.GetDataset(sql);

            if (ds.Tables.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    ddObject.Items.Add(new ListItem(dr["object_name"].ToString(), dr["af_row_id"].ToString()));
                }
            }
            hdd = null;
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("loadObjects : Error : " + ex.Message);
        }
    }

    private void loadDefaultValues()
    {
        try
        {
            ddOperator1.Items.Clear();
            ddOperator2.Items.Clear();
            ddOperator1.Items.Add(new ListItem("--None--", ""));
            ddOperator2.Items.Add(new ListItem("--None--", ""));
            ddOperator3.Items.Add(new ListItem("--None--", ""));
            ddOperator4.Items.Add(new ListItem("--None--", ""));
            ddOperator5.Items.Add(new ListItem("--None--", ""));
            string[] opers = new string[] { "equals", "not equal to", "starts with", "contain", "does not contain", "less than", "greater than", "less or equal", "greater or equal" };
            string[] operValues = new string[] { "= '%C%'", "<> '%C%'", "like '%C%%'", "like '%%C%%'", "not like '%%C%%'", "< '%C%'", "> '%C%'", "<= '%C%'", ">= '%C%'" };
            for (int i = 0; i < opers.Length; i++)
            {
                ddOperator1.Items.Add(new ListItem(opers[i], operValues[i]));
                ddOperator2.Items.Add(new ListItem(opers[i], operValues[i]));
                ddOperator3.Items.Add(new ListItem(opers[i], operValues[i]));
                ddOperator4.Items.Add(new ListItem(opers[i], operValues[i]));
                ddOperator5.Items.Add(new ListItem(opers[i], operValues[i]));
            }
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("loadDefaultValues : Error : " + ex.Message);
        }
    }

    protected void Page_PreInit(object sender, EventArgs e)
    {
        this.Theme = Session["Theme"].ToString();
        this.Title = "MaxBlox";//this.Title = "MaxBlox - Workflow";
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        //if (Session["dtWorkflow"] != null)
        //    if (!IsPostBack)
        //        Response.Redirect(Request.UrlReferrer.ToString());
        try
        {
            security hdds = new security();
            lbl_space_1.Text = "<br />";
            if (Session["userid"] == null) Response.Redirect(hdds.SessionExpiryURL);
            if (Session["userid"].ToString() == "") Response.Redirect(hdds.SessionExpiryURL);

            //Code added by Sampath on 18-Nov-2011 for IPP Vertical privilege
            if (Request.QueryString["mn"] != null)
            {
                if (!hdds.checkObjectMenuAccess(Request.QueryString["mn"]))
                {
                    tblcontrols.Visible = false;
                    lbl_message.Text = wrapItAsMessage("<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;You do not have sufficient access permission.", true);
                    return;
                }
            }

            //Code added by Sampath on 15-Nov-2011 for IPP Vertical privilege
            if (Request.QueryString["PK"] != null && Request.QueryString["pgs_id"] != null)
            {
                if (!hdds.checkRecordAccess(Request.QueryString["PK"].ToString(), Request.QueryString["pgs_id"].ToString()))
                {
                    lbl_message.Text = wrapItAsMessage("<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;You do not have sufficient access permission.", true);
                    tblcontrols.Visible = false;
                    return;
                }
            }

            setRequestUrl();

            if (Request.QueryString["mn"] != null)
                hdds.logMenuClick(Request.QueryString["mn"].ToString());
            if (this.Master.FindControl("Form1") != null)
            {
                frmObj = (HtmlForm)this.Master.FindControl("Form1");
            }
            if (!Page.IsPostBack)
            {
                loadOwneridDropDown();
            }

            CheckForChangeOwner();

            getTables();
            CheckEditOperation();
            hdds = null;
            getpageicons(); // added by srivatsan
            isViewMode();
            //fillchkboxAdditionalFields();
        }
        catch (Exception Ex)
        {
            LogWriter.WriteLog("Page_Load : Error : " + Ex.Message);
        }
    }

    private void isViewMode()
    {
        try
        {
            if (HttpContext.Current.Request.QueryString["VMODE"] != null)
                if (HttpContext.Current.Request.QueryString["VMODE"] == "1")
                {
                    DynamicDisplayI ddi = new DynamicDisplayI();
                    HtmlTable ht = (HtmlTable)frmObj.FindControl("ContentPlaceHolder3").FindControl("tblcontrols");
                    ddi.disableControls(ht);
                    ddi = null;
                    lblHeader.Text = "Workflow Ruleset - View";// added by Prithi on Aug-04-2008

                    //srivatsan
                    lbl_message.Visible = false;
                    lstDeletedRules.Visible = false;
                    lstResetTriggers.Visible = false;
                }
        }
        catch (Exception Ex)
        {
            LogWriter.WriteLog("isViewMode : Error : " + Ex.Message);
        }
    }

    private void getTables()
    {
        try
        {
            HDDatabase HDD = new HDDatabase();
            string sSql = "Select * from sy_org_structure";
            dsWorkflow.Tables.Add(HDD.GetDataTable(sSql, "sy_org_structure").Copy());
            sSql = "select * from sy_usr";
            dsWorkflow.Tables.Add(HDD.GetDataTable(sSql, "sy_usr").Copy());
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("getTables : Error : " + ex.Message);
        }
    }

    private void setRequestUrl()
    {
        //if (Request.UrlReferrer != null)
        //    hfRequestURL.Value = Request.UrlReferrer.AbsoluteUri;
        //else
        hfRequestURL.Value = "DisplayGrid.aspx?pgs_id=" + Request.QueryString["pgs_id"] + "&mn=" + Request.QueryString["mn"];
    }

    private void CheckEditOperation()
    {
        try
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["PK"] == null)
                {
                    //btnUpdate.Visible = false;
                    hf_ruleset_af_row_id.Value = getHashKey();
                    lblHeader.Text = "Workflow Ruleset - Add";
                    //ddownerid.SelectedValue = Session["user_afrowid"].ToString();
                    ownerid.Value = Session["user_afrowid"].ToString();
                    txt_ownerid.Text = Session["userid"].ToString();
                }
                else
                {
                    if (Request.QueryString["CPY"] != null)
                    {
                        //IsCopy = true;
                        //IsEdit = false;
                        lblHeader.Text = "Workflow Ruleset - Copy";
                        hf_ruleset_af_row_id.Value = getHashKey();
                    }
                    else
                    {
                        //IsEdit = true;
                        //btnSave.Visible = false;
                        lblHeader.Text = "Workflow Ruleset - Edit";
                        hf_ruleset_af_row_id.Value = Request.QueryString["PK"];
                    }

                    if (!IsPostBack)
                    {
                        DataSet dsInputInfo = new DataSet();
                        if (getData(ref dsInputInfo))
                        {
                            setData(ref dsInputInfo);
                        }
                    }
                }
            }

            if (Request.QueryString["PK"] == null)
                btnUpdate.Visible = false;
            else
            {
                if (Request.QueryString["CPY"] != null)
                {
                    IsCopy = true;
                    IsEdit = false;
                    btnUpdate.Visible = false;
                }
                else
                {
                    IsEdit = true;
                    btnSave.Visible = false;
                }
            }
        }

        catch (Exception Ex)
        {
            LogWriter.WriteLog("CheckEditOperation : Error : " + Ex.Message);
        }
    }

    private bool getChildRecords(string sSql, string sPage_id, ref DataSet dsInputInfo, HDDatabase HDD)
    {
        bool bReturn = true;
        try
        {
            DataRow drTemp = HDD.GetTableRow(sSql);
            if (drTemp != null)
            {
                if (dsInputInfo.Tables[sPage_id] == null)
                {
                    DataTable dtTemp = drTemp.Table.Clone();
                    dtTemp.TableName = sPage_id;
                    dsInputInfo.Tables.Add(dtTemp);
                    dtTemp = null;
                }
                dsInputInfo.Tables[sPage_id].ImportRow(drTemp);
            }
            drTemp = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getChildRecords : Error : " + ex.Message);
            bReturn = false;
        }
        return bReturn;
    }

    private bool getData(ref DataSet dsInputInfo)
    {
        bool bReturn = true;
        try
        {
            //DataSet dsPageInfo = getPagesetInfo();
            //DataSet dsInputInfo = getDataset(dsPageInfo);
            //DataSet dsInputInfo = new DataSet();
            HDDatabase HDD = new HDDatabase();

            //string[] s_Pageids = new string[] { "p_workflow_ruleset_1", "p_workflow_rules", "p_workflow_triggers" };//, "p_work_item", "p_field_updates" };
            //string[] sSQLs = new string[] { "select * from bu_workflow_ruleset_1 where af_row_id='" + Request.QueryString["PK"] + "'", "select * from sy_workflow_rules where ruleset='" + Request.QueryString["PK"] + "'", "select * from sy_workflow_triggers where ruleset_id='" + Request.QueryString["PK"] + "'" };
            string[] s_Pageids = new string[] { "p_workflow_ruleset", "p_workflow_rules", "p_workflow_triggers", "p_workitem_additional_info" };//, "p_work_item", "p_field_updates" };
            string[] sSQLs = new string[] { "select * from sy_workflow_ruleset where af_row_id='" + Request.QueryString["PK"] + "'", "select * from sy_workflow_rules where ruleset='" + Request.QueryString["PK"] + "'", "select * from sy_workflow_triggers where ruleset_id='" + Request.QueryString["PK"] + "'", "select * from sy_workitem_additional_info where ruleset_id ='" + Request.QueryString["PK"] + "'" };
            string sSql = "";
            for (int iCount = 0; iCount < sSQLs.Length; iCount++)
            {
                ///string sSql = sSQLs[iCount]; 
                dsInputInfo.Tables.Add(HDD.GetDataTable(sSQLs[iCount], s_Pageids[iCount]).Copy());
            }
            //added by Sampath on 10-Nov-2011 for Encoding
            //CommonFunctions.decodeData(dsInputInfo);

            foreach (DataRow dr in dsInputInfo.Tables[s_Pageids[1]].Rows)
            {
                sSql = "select * from sy_work_item where rule_id = '" + dr["af_row_id"].ToString() + "'";
                getChildRecords(sSql, "p_work_item", ref dsInputInfo, HDD);
                sSql = "select * from sy_field_updates where rule_id = '" + dr["af_row_id"].ToString() + "'";
                getChildRecords(sSql, "p_field_updates", ref dsInputInfo, HDD);
                sSql = "select * from sy_reject_field_updates where rule_id = '" + dr["af_row_id"].ToString() + "'";
                getChildRecords(sSql, "p_reject_field_updates", ref dsInputInfo, HDD);
                // Added by John Sathish
                sSql = "select * from sy_workflow_action where rule_id = '" + dr["af_row_id"].ToString() + "'";
                getChildRecords(sSql, "p_workflow_action", ref dsInputInfo, HDD);
                //dsInputInfo.Tables.Add(HDD.GetDataTable(sSql, "p_workflow_action").Copy());
                // Up to this
                /*sSql = "select * from sy_work_item where rule_id = '" + dr["af_row_id"].ToString() + "'";
                DataRow drTemp = HDD.GetTableRow(sSql);
                if (dsInputInfo.Tables["p_work_item"] == null)
                {
                    DataTable dtTemp = drTemp.Table.Clone();
                    dtTemp.TableName = "p_work_item";
                    dsInputInfo.Tables.Add(dtTemp);
                    dtTemp = null;
                }
                dsInputInfo.Tables["p_work_item"].ImportRow(drTemp);
                drTemp = null;
                sSql = "select * from sy_field_updates where rule_id = '" + dr["af_row_id"].ToString() + "'";
                drTemp = HDD.GetTableRow(sSql);
                if (dsInputInfo.Tables["p_field_updates"] == null)
                {
                    DataTable dtTemp = drTemp.Table.Clone();
                    dtTemp.TableName = "p_field_updates";
                    dsInputInfo.Tables.Add(dtTemp);
                    dtTemp = null;
                }
                dsInputInfo.Tables["p_field_updates"].ImportRow(drTemp);
                drTemp = null;*/
            }

            if (dsInputInfo.Tables["p_field_updates"] == null)
            {
                DataSet dsPS = new DataSet();
                DataSet dsData = new DataSet();
                PageInfoLoad PIL = new PageInfoLoad();
                dsPS = PIL.GetPageSetPageCtrlInfo("c1a9c453ec289bcc"); // field_updates
                ScreenReader SR = new ScreenReader();
                SR.CreatePageDataTable(dsData, dsPS.Tables["page"], dsPS.Tables["pagectrl"]);
                SR = null;
                dsData.Tables[0].TableName = "p_field_updates";
                dsInputInfo.Tables.Add(dsData.Tables["p_field_updates"].Copy());
                dsPS.Dispose();
                dsData.Dispose();
                PIL = null;
                SR = null;
            }

            if (dsInputInfo.Tables["p_reject_field_updates"] == null)
            {
                DataSet dsPS = new DataSet();
                DataSet dsData = new DataSet();
                PageInfoLoad PIL = new PageInfoLoad();
                dsPS = PIL.GetPageSetPageCtrlInfo("37a591e71da6620c"); // reject_field_updates
                ScreenReader SR = new ScreenReader();
                SR.CreatePageDataTable(dsData, dsPS.Tables["page"], dsPS.Tables["pagectrl"]);
                SR = null;
                dsData.Tables[0].TableName = "p_reject_field_updates";
                dsInputInfo.Tables.Add(dsData.Tables["p_reject_field_updates"].Copy());
                dsPS.Dispose();
                dsData.Dispose();
                PIL = null;
                SR = null;
            }
            // Added by John Sathish
            //if (dsInputInfo.Tables["p_workflow_action"] == null)
            //{
            //    DataSet dsPS = new DataSet();
            //    DataSet dsData = new DataSet();
            //    PageInfoLoad PIL = new PageInfoLoad();
            //    dsPS = PIL.GetPageSetPageCtrlInfo("workflow_action");
            //    ScreenReader SR = new ScreenReader();
            //    SR.CreatePageDataTable(dsData, dsPS.Tables["page"], dsPS.Tables["pagectrl"]);
            //    SR = null;
            //    dsData.Tables[0].TableName = "p_workflow_action";
            //    dsInputInfo.Tables.Add(dsData.Tables["p_workflow_action"].Copy());
            //    dsPS.Dispose();
            //    dsData.Dispose();
            //    PIL = null;
            //    SR = null;
            //}
            //Up to this

            HDD = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getData : Error : " + ex.Message);
            bReturn = false;
        }
        return bReturn;
    }

    private bool setData(ref DataSet dsInputInfo)
    {
        bool bReturn = true;
        try
        {
            string Page_Id = "p_workflow_ruleset";
            txtRulesetName.Text = dsInputInfo.Tables[Page_Id].Rows[0]["name"].ToString();//p_workflow_ruleset
            txtRulesetDesc.Text = dsInputInfo.Tables[Page_Id].Rows[0]["description"].ToString();
            ddlbased_on.Text = dsInputInfo.Tables[Page_Id].Rows[0]["based_on"].ToString();
            resetRule();
            ddObject.SelectedValue = dsInputInfo.Tables[Page_Id].Rows[0]["object_id"].ToString();
            //ddownerid.SelectedValue = dsInputInfo.Tables[Page_Id].Rows[0]["owner_id"].ToString(); // Added by srivatsan for owner id
            setOwnerValues(dsInputInfo.Tables[Page_Id].Rows[0]["owner_id"].ToString());
            if (dsInputInfo.Tables[Page_Id].Columns.Contains("skip_title"))
                chkSkipRule.Checked = dsInputInfo.Tables[Page_Id].Rows[0]["skip_title"].ToString() == "" ? false : Boolean.Parse(dsInputInfo.Tables["p_workflow_ruleset"].Rows[0]["skip_title"].ToString());
            chkApplyChilds.Checked = dsInputInfo.Tables[Page_Id].Rows[0]["apply_for_childs"].ToString() == "" ? false : Boolean.Parse(dsInputInfo.Tables["p_workflow_ruleset"].Rows[0]["apply_for_childs"].ToString());//
            ddEvent.SelectedValue = dsInputInfo.Tables[Page_Id].Rows[0]["event"].ToString();
            getAllFields(ddObject.SelectedValue);
            //dsInputInfo.Tables["p_workflow_ruleset"].Rows[0][""].ToString();

            ddField1.SelectedValue = dsInputInfo.Tables["p_workflow_triggers"].Rows[0]["field"].ToString();
            ddOperator1.SelectedValue = dsInputInfo.Tables["p_workflow_triggers"].Rows[0]["operator"].ToString();
            txtValue1.Text = dsInputInfo.Tables["p_workflow_triggers"].Rows[0]["value"].ToString();
            ddand_or1.SelectedValue = dsInputInfo.Tables["p_workflow_triggers"].Rows[0]["and_or"].ToString();
            if (dsInputInfo.Tables["p_workflow_triggers"].Rows.Count > 1)
            {
                ddField2.SelectedValue = dsInputInfo.Tables["p_workflow_triggers"].Rows[1]["field"].ToString();
                ddOperator2.SelectedValue = dsInputInfo.Tables["p_workflow_triggers"].Rows[1]["operator"].ToString();
                txtValue2.Text = dsInputInfo.Tables["p_workflow_triggers"].Rows[1]["value"].ToString();
                ddand_or2.SelectedValue = dsInputInfo.Tables["p_workflow_triggers"].Rows[1]["and_or"].ToString();
            }
            if (dsInputInfo.Tables["p_workflow_triggers"].Rows.Count > 2)
            {
                ddField3.SelectedValue = dsInputInfo.Tables["p_workflow_triggers"].Rows[2]["field"].ToString();
                ddOperator3.SelectedValue = dsInputInfo.Tables["p_workflow_triggers"].Rows[2]["operator"].ToString();
                txtValue3.Text = dsInputInfo.Tables["p_workflow_triggers"].Rows[2]["value"].ToString();
                ddand_or3.SelectedValue = dsInputInfo.Tables["p_workflow_triggers"].Rows[2]["and_or"].ToString();
            }
            if (dsInputInfo.Tables["p_workflow_triggers"].Rows.Count > 3)
            {
                ddField4.SelectedValue = dsInputInfo.Tables["p_workflow_triggers"].Rows[3]["field"].ToString();
                ddOperator4.SelectedValue = dsInputInfo.Tables["p_workflow_triggers"].Rows[3]["operator"].ToString();
                txtValue4.Text = dsInputInfo.Tables["p_workflow_triggers"].Rows[3]["value"].ToString();
                ddand_or4.SelectedValue = dsInputInfo.Tables["p_workflow_triggers"].Rows[3]["and_or"].ToString();
            }
            if (dsInputInfo.Tables["p_workflow_triggers"].Rows.Count > 4)
            {
                ddField5.SelectedValue = dsInputInfo.Tables["p_workflow_triggers"].Rows[4]["field"].ToString();
                ddOperator5.SelectedValue = dsInputInfo.Tables["p_workflow_triggers"].Rows[4]["operator"].ToString();
                txtValue5.Text = dsInputInfo.Tables["p_workflow_triggers"].Rows[4]["value"].ToString();
            }

            DataTable dtWorkFlow = createDataTable4Workflow();
            foreach (DataRow dr in dsInputInfo.Tables["p_workflow_rules"].Select("", "sequence asc"))
            {
                //"af_row_id", "RuleName", "SourceTitle", "TargetTitle", "AddWorkItem", "WI_Message", "addFieldUpdate", "FieldUpdateField", "FieldUpdateValue"
                DataRow drNew = dtWorkFlow.NewRow();
                drNew["af_row_id"] = dr["af_row_id"].ToString();
                drNew["RuleName"] = dr["name"].ToString();
                /*drNew["SourceTitle"] = dr["source_title"].ToString();
                drNew["TargetTitle"] = dr["target_title"].ToString();*/

                if (drNew.Table.Columns.Contains("Target"))
                    drNew["Target"] = dr["Target"];

                string sSource = "";
                string sTarget = "";

                if (ddlbased_on.Text.ToLower() == "title")
                {
                    sSource = getColumnValue("sy_org_structure", "af_row_id", dr["source_title"].ToString(), "title");
                }
                else if (ddlbased_on.Text.ToLower() == "user")
                {
                    sSource = getColumnValue("sy_usr", "af_row_id", dr["source_title"].ToString(), "user_id");
                }

                dr["source_title"] = sSource;//afrowid

                if (dr["Target"].ToString().ToLower() == "title")
                {
                    sTarget = getColumnValue("sy_org_structure", "af_row_id", dr["target_title"].ToString(), "title");
                }
                else if (dr["Target"].ToString().ToLower() == "user")
                {
                    sTarget = getColumnValue("sy_usr", "af_row_id", dr["target_title"].ToString(), "user_id");
                }
                else if (dr["Target"].ToString().ToLower() == "user_from_field")
                {
                    HDDatabase HDD = new HDDatabase();
                    String sSql = "select attrib_id from sy_obj_att where af_row_id='" + dr["target_title"].ToString() + "'";
                    string sTemp = HDD.GetColumnValue(sSql);
                    sTarget = sTemp;
                    HDD = null;//sTarget = dRow["TargetTitle"].ToString();
                }

                drNew["SourceTitle"] = sSource;
                drNew["TargetTitle"] = sTarget;

                DataRow[] drSelect = dsInputInfo.Tables["p_work_item"].Select("rule_id='" + dr["af_row_id"].ToString() + "'");
                if (drSelect.Length > 0)
                {
                    drNew["AddWorkItem"] = "true";
                    drNew["WI_message"] = drSelect[0]["message"].ToString();
                }

                if (dsInputInfo.Tables["p_field_updates"] != null)
                {
                    drSelect = dsInputInfo.Tables["p_field_updates"].Select("rule_id='" + dr["af_row_id"].ToString() + "'");

                    if (drSelect.Length > 0)
                    {
                        if (drSelect[0]["field_name"].ToString() != "--None--" && drSelect[0]["field_name"].ToString() != "")
                        {
                            drNew["addFieldUpdate"] = "true";
                        }
                        drNew["FieldUpdateField"] = drSelect[0]["field_name"].ToString();
                        drNew["FieldUpdateValue"] = drSelect[0]["field_value"].ToString();
                    }
                }

                if (dsInputInfo.Tables["p_reject_field_updates"] != null)
                {
                    drSelect = dsInputInfo.Tables["p_reject_field_updates"].Select("rule_id='" + dr["af_row_id"].ToString() + "'");

                    if (drSelect.Length > 0)
                    {
                        if (drSelect[0]["field_name"].ToString() != "--None--" && drSelect[0]["field_name"].ToString() != "")
                        {
                            drNew["addFieldUpdateReject"] = "true";
                        }
                        drNew["FieldUpdateFieldReject"] = drSelect[0]["field_name"].ToString();
                        drNew["FieldUpdateValueReject"] = drSelect[0]["field_value"].ToString();
                    }
                }

                //Added by John Sathish
                if (dsInputInfo.Tables["p_workflow_action"] != null)
                {
                    drSelect = dsInputInfo.Tables["p_workflow_action"].Select("rule_id='" + dr["af_row_id"].ToString() + "'");

                    if (drSelect.Length > 0)
                    {
                        if (drSelect[0]["parameter"].ToString() != "" && drSelect[0]["action_event"].ToString() != "")
                        {
                            HDDatabase hdd = new HDDatabase();
                            if (drSelect[0]["action_event"].ToString() == "OA")
                            {
                                drNew["addFieldEmail"] = "true";
                                drNew["FieldEmailTemplate"] = hdd.GetColumnValue("sy_email_template", "name", "af_row_id='" + drSelect[0]["parameter"].ToString() + "'");
                            }
                            else if (drSelect[0]["action_event"].ToString() == "OR")
                            {
                                drNew["addFieldEmailRej"] = "true";
                                drNew["FieldEmailTemplateRej"] = hdd.GetColumnValue("sy_email_template", "name", "af_row_id='" + drSelect[0]["parameter"].ToString() + "'");
                            }
                        }
                    }
                    if (drSelect.Length == 2)
                    {
                        if (drSelect[1]["parameter"].ToString() != "" && drSelect[1]["action_event"].ToString() != "")
                        {
                            HDDatabase hdd = new HDDatabase();
                            if (drSelect[1]["action_event"].ToString() == "OA")
                            {
                                drNew["addFieldEmail"] = "true";
                                drNew["FieldEmailTemplate"] = hdd.GetColumnValue("sy_email_template", "name", "af_row_id='" + drSelect[1]["parameter"].ToString() + "'");
                            }
                            else if (drSelect[1]["action_event"].ToString() == "OR")
                            {
                                drNew["addFieldEmailRej"] = "true";
                                drNew["FieldEmailTemplateRej"] = hdd.GetColumnValue("sy_email_template", "name", "af_row_id='" + drSelect[1]["parameter"].ToString() + "'");
                            }
                        }
                    }
                }
                //Up to this

                dtWorkFlow.Rows.Add(drNew);
                drNew = null;
                drSelect = null;
            }

            fillchkboxAdditionalFields(); // Added by srivatsan on Jan 29

            Session["dtWorkflow"] = dtWorkFlow;
            loadRules();
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("setData : Error : " + ex.Message);
            bReturn = false;
        }
        return bReturn;
    }

    private bool validate()
    {
        try
        {
            lblstatus.Text = "";
            if (txtRulesetName.Text.Trim() == "")
            {
                lblstatus.Text = wrapItAsMessage("RulesetName is a mandatory field.", true);
                return false;
            }
            if (ddObject.SelectedValue.Trim() == "")
            {
                lblstatus.Text = wrapItAsMessage("Select an object to proceed.", true);
                return false;
            }
            if (Session["dtWorkflow"] == null)
            {
                lblstatus.Text = wrapItAsMessage("At least one rule is mandatory to create a Ruleset.", true);
                return false;
            }
            DataTable dt = (DataTable)Session["dtWorkflow"];
            DataTable dtTemp = dt.Clone();

            if (lstDeletedRules.Items.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                    if (lstDeletedRules.Items.FindByText(dr["af_row_id"].ToString()) == null)
                    {
                        dtTemp.ImportRow(dr);
                    }
            }
            else//included by sanal on June 10, 2008 - consider all records if no rule is deleted
            {
                foreach (DataRow dr in dt.Rows)
                {
                    dtTemp.ImportRow(dr);
                }
            }

            if (dtTemp.Rows.Count < 1)
            {
                dtTemp.Dispose();
                dtTemp = null;
                dt.Dispose();
                dt = null;
                lblstatus.Text = wrapItAsMessage("At least one rule is mandatory to create a Ruleset.", true);
                return false;
            }

            if (!validateOwnerid())
            {
                return false;
            }
            dtTemp.Dispose();
            dtTemp = null;
            dt.Dispose();
            dt = null;
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("validate : Error : " + ex.Message);
        }
        return true;
    }

    private DataSet getDataset(DataSet dsPageInfo)
    {
        DataSet dsInputInfo = new DataSet();
        try
        {
            ScreenReader objSR = new ScreenReader();
            objSR.CreatePageDataTable(dsInputInfo, dsPageInfo.Tables["page"], dsPageInfo.Tables["pagectrl"]);
            objSR = null;
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("getDataset : Error : " + ex.Message);
        }
        return dsInputInfo;
    }

    private DataSet getPagesetInfo()
    {
        DataSet dsPageInfo = null;
        try
        {
            DataSet dsPageInfoTemp = null;
            PageInfoLoad objPIL = new PageInfoLoad();
            //string[] s_Pagesets = new string[] { "workflow_ruleset_1", "workflow_rules", "workflow_triggers", "work_item", "field_updates", "reject_field_updates" };
            //string[] s_Pagesets = new string[] { "workflow_ruleset", "workflow_rules", "workflow_triggers", "work_item", "field_updates", "reject_field_updates", "workitem_additional_info", "workflow_action" }; // Modified by srivatsan //Added by John Sathish
            string[] s_Pagesets = new string[] { "38ee59900591c5a7", "eb23d3fcf5911d62", "f50abe7653ed667a", "99b41878b0e1812a", "c1a9c453ec289bcc", "37a591e71da6620c", "528cb5a76f032164", "4f37635cc199e149" }; // Modified by srivatsan //Added by John Sathish
            foreach (string sPageset in s_Pagesets)
            {
                dsPageInfoTemp = objPIL.GetPageSetPageCtrlInfo(sPageset);
                if (dsPageInfo == null)
                    dsPageInfo = dsPageInfoTemp;
                else
                {
                    dsPageInfo.Tables["Page"].Merge(dsPageInfoTemp.Tables["Page"]);
                    dsPageInfo.Tables["PageCtrl"].Merge(dsPageInfoTemp.Tables["PageCtrl"]);
                    dsPageInfo.Tables["PageKeys"].Merge(dsPageInfoTemp.Tables["PageKeys"]);
                }
            }
            objPIL = null;
            dsPageInfoTemp.Dispose();
            dsPageInfoTemp = null;
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("getPagesetInfo : Error : " + ex.Message);
        }
        return dsPageInfo;
    }

    private void fillDefaultColumns(ref DataRow dr, string sCurrentDate)
    {
        if (dr["created_by"] == DBNull.Value)
        {
            dr["created_by"] = Session["user_afrowid"].ToString();
            dr["created_at"] = sCurrentDate;
        }
        /*if (!IsEdit)
        {
            dr["created_by"] = Session["user_afrowid"].ToString();
            dr["created_at"] = sCurrentDate;
        }*/
        dr["modified_by"] = Session["user_afrowid"].ToString();
        dr["modified_at"] = sCurrentDate;

        //dr["owner_id"] = ddownerid.SelectedValue;
        string userafrowid = getUseraf_row_idfromUser(txt_ownerid.Text);
        if (userafrowid != "")
        {
            ownerid.Value = userafrowid;
            dr["owner_id"] = ownerid.Value;
        }
        else
        {
            lbl_message.Text = wrapItAsMessage("&nbsp;<img src='Images/Error.gif' border='0'>&nbsp;Invalid data for Owner :" + HttpUtility.HtmlEncode(txt_ownerid.Text), true);
            return;
        }

    }

    private void getRowForEdit(ref DataSet dsInputInfo, ref DataRow dr, string sTableName, int Sequence)
    {
        if (IsEdit && Sequence < dsInputInfo.Tables[sTableName].Rows.Count)
            dr = dsInputInfo.Tables[sTableName].Rows[Sequence];
        else
        {
            dr = dsInputInfo.Tables[sTableName].NewRow();
        }
    }

    private void fillPageData(ref DataSet dsInputInfo)
    {
        try
        {
            string sCurrentDate = DateTime.Now.ToString();

            if (IsEdit || IsCopy)
                getData(ref dsInputInfo);
            DataRow dr = null;
            //add workflow ruleset
            string Page_id = "p_workflow_ruleset";
            if (dsInputInfo.Tables[Page_id] != null)
            {
                getRowForEdit(ref dsInputInfo, ref dr, Page_id, 0);

                dr["name"] = txtRulesetName.Text;
                dr["description"] = txtRulesetDesc.Text;
                dr["based_on"] = ddlbased_on.Text;
                dr["object_id"] = ddObject.SelectedValue;
                if (dr.Table.Columns.Contains("skip_title"))
                    dr["skip_title"] = chkSkipRule.Checked;

                dr["apply_for_childs"] = chkApplyChilds.Checked == true ? true : false;
                dr["event"] = ddEvent.SelectedValue;
                fillDefaultColumns(ref dr, sCurrentDate);

                if (!IsEdit)
                {
                    dr["af_row_id"] = hf_ruleset_af_row_id.Value;
                    dsInputInfo.Tables[Page_id].Rows.Add(dr);
                }
                dr = null;
            }

            //add WorkFlow Triggers
            if (dsInputInfo.Tables["p_workflow_triggers"] != null)
            {
                getRowForEdit(ref dsInputInfo, ref dr, "p_workflow_triggers", 0);

                dr["Ruleset_ID"] = hf_ruleset_af_row_id.Value;
                dr["sequence"] = 1;
                dr["field"] = ddField1.SelectedValue;
                dr["operator"] = ddOperator1.SelectedValue;
                dr["value"] = txtValue1.Text;
                dr["and_or"] = ddand_or1.SelectedValue;
                fillDefaultColumns(ref dr, sCurrentDate);
                if (!IsEdit)
                {
                    dr["af_row_id"] = getHashKey();
                    dsInputInfo.Tables["p_workflow_triggers"].Rows.Add(dr);
                }
                dr = null;
                if (ddField2.SelectedValue != "")
                {
                    getRowForEdit(ref dsInputInfo, ref dr, "p_workflow_triggers", 1);

                    dr["Ruleset_ID"] = hf_ruleset_af_row_id.Value;
                    dr["sequence"] = 2;
                    dr["field"] = ddField2.SelectedValue;
                    dr["operator"] = ddOperator2.SelectedValue;
                    dr["value"] = txtValue2.Text;
                    dr["and_or"] = ddand_or2.SelectedValue;
                    fillDefaultColumns(ref dr, sCurrentDate);
                    if (dsInputInfo.Tables["p_workflow_triggers"].Select("af_row_id='" + dr["af_row_id"].ToString() + "'").Length == 0)
                    {
                        dr["af_row_id"] = getHashKey();
                        dsInputInfo.Tables["p_workflow_triggers"].Rows.Add(dr);
                    }
                    dr = null;
                }
                else
                {
                    getRowForEdit(ref dsInputInfo, ref dr, "p_workflow_triggers", 1);
                    if (dr != null)
                        if (dr["af_row_id"].ToString() != "")
                            lstResetTriggers.Items.Add(dr["af_row_id"].ToString());
                }

                if (ddField3.SelectedValue != "")
                {
                    getRowForEdit(ref dsInputInfo, ref dr, "p_workflow_triggers", 2);

                    dr["Ruleset_ID"] = hf_ruleset_af_row_id.Value;
                    dr["sequence"] = 3;
                    dr["field"] = ddField3.SelectedValue;
                    dr["operator"] = ddOperator3.SelectedValue;
                    dr["value"] = txtValue3.Text;
                    dr["and_or"] = ddand_or3.SelectedValue;
                    fillDefaultColumns(ref dr, sCurrentDate);
                    if (dsInputInfo.Tables["p_workflow_triggers"].Select("af_row_id='" + dr["af_row_id"].ToString() + "'").Length == 0)
                    {
                        dr["af_row_id"] = getHashKey();
                        dsInputInfo.Tables["p_workflow_triggers"].Rows.Add(dr);
                    }
                    dr = null;
                }
                else
                {
                    getRowForEdit(ref dsInputInfo, ref dr, "p_workflow_triggers", 2);
                    if (dr != null)
                        if (dr["af_row_id"].ToString() != "")
                            lstResetTriggers.Items.Add(dr["af_row_id"].ToString());
                }

                if (ddField4.SelectedValue != "")
                {
                    getRowForEdit(ref dsInputInfo, ref dr, "p_workflow_triggers", 3);

                    dr["Ruleset_ID"] = hf_ruleset_af_row_id.Value;
                    dr["sequence"] = 4;
                    dr["field"] = ddField4.SelectedValue;
                    dr["operator"] = ddOperator4.SelectedValue;
                    dr["value"] = txtValue4.Text;
                    dr["and_or"] = ddand_or4.SelectedValue;
                    fillDefaultColumns(ref dr, sCurrentDate);
                    if (dsInputInfo.Tables["p_workflow_triggers"].Select("af_row_id='" + dr["af_row_id"].ToString() + "'").Length == 0)
                    {
                        dr["af_row_id"] = getHashKey();
                        dsInputInfo.Tables["p_workflow_triggers"].Rows.Add(dr);
                    }
                    dr = null;
                }
                else
                {
                    getRowForEdit(ref dsInputInfo, ref dr, "p_workflow_triggers", 3);
                    if (dr != null)
                        if (dr["af_row_id"].ToString() != "")
                            lstResetTriggers.Items.Add(dr["af_row_id"].ToString());
                }

                if (ddField5.SelectedValue != "")
                {
                    getRowForEdit(ref dsInputInfo, ref dr, "p_workflow_triggers", 4);

                    dr["Ruleset_ID"] = hf_ruleset_af_row_id.Value;
                    dr["sequence"] = 5;
                    dr["field"] = ddField5.SelectedValue;
                    dr["operator"] = ddOperator5.SelectedValue;
                    dr["value"] = txtValue5.Text;
                    fillDefaultColumns(ref dr, sCurrentDate);
                    if (dsInputInfo.Tables["p_workflow_triggers"].Select("af_row_id='" + dr["af_row_id"].ToString() + "'").Length == 0)
                    {
                        dr["af_row_id"] = getHashKey();
                        dsInputInfo.Tables["p_workflow_triggers"].Rows.Add(dr);
                    }
                    dr = null;
                }
                else
                {
                    getRowForEdit(ref dsInputInfo, ref dr, "p_workflow_triggers", 4);
                    if (dr != null)
                        if (dr["af_row_id"].ToString() != "")
                            lstResetTriggers.Items.Add(dr["af_row_id"].ToString());
                }
            }

            if (dsInputInfo.Tables["p_workflow_rules"] == null) getDataTable(ref dsInputInfo, "eb23d3fcf5911d62", "p_workflow_rules"); // workflow_rules
            if (dsInputInfo.Tables["p_work_item"] == null) getDataTable(ref dsInputInfo, "99b41878b0e1812a", "p_work_item"); // work_item
            if (dsInputInfo.Tables["p_field_updates"] == null) getDataTable(ref dsInputInfo, "c1a9c453ec289bcc", "p_field_updates"); // field_updates
            if (dsInputInfo.Tables["p_reject_field_updates"] == null) getDataTable(ref dsInputInfo, "p_reject_field_updates", "p_reject_field_updates");
            //Added by John Sathish
            if (dsInputInfo.Tables["p_workflow_action"] == null) getDataTable(ref dsInputInfo, "4f37635cc199e149", "p_workflow_action"); // workflow_action
            //Up to this

            if (dsInputInfo.Tables["p_workflow_rules"] != null)
            {
                DataTable dt = (DataTable)Session["dtWorkflow"];

                foreach (ListItem li in lstDeletedRules.Items)
                {
                    if (dsInputInfo.Tables["p_workflow_rules"].Select("af_row_id='" + li.Text + "'").Length > 0)
                    {
                        dsInputInfo.Tables["p_workflow_rules"].Rows.Remove(dsInputInfo.Tables["p_workflow_rules"].Select("af_row_id='" + li.Text + "'")[0]);
                        dsInputInfo.Tables["p_work_item"].Rows.Remove(dsInputInfo.Tables["p_work_item"].Select("rule_id='" + li.Text + "'")[0]);
                        if (dsInputInfo.Tables["p_field_updates"].Select("rule_id='" + li.Text + "'").Length > 0)
                            dsInputInfo.Tables["p_field_updates"].Rows.Remove(dsInputInfo.Tables["p_field_updates"].Select("rule_id='" + li.Text + "'")[0]);
                        if (dsInputInfo.Tables["p_reject_field_updates"].Select("rule_id='" + li.Text + "'").Length > 0)
                            dsInputInfo.Tables["p_reject_field_updates"].Rows.Remove(dsInputInfo.Tables["p_reject_field_updates"].Select("rule_id='" + li.Text + "'")[0]);
                        //Added by John Sathish
                        if (dsInputInfo.Tables["p_workflow_action"].Select("rule_id='" + li.Text + "'").Length > 0)
                            dsInputInfo.Tables["p_workflow_action"].Rows.Remove(dsInputInfo.Tables["p_workflow_action"].Select("rule_id='" + li.Text + "'")[0]);
                        //Up to this
                    }
                    if (dt.Select("af_row_id='" + li.Text + "'").Length > 0)
                        dt.Rows.Remove(dt.Select("af_row_id='" + li.Text + "'")[0]);
                }
                //lstDeletedRules.Items.Clear();

                for (int iRow = 0; iRow < dt.Rows.Count; iRow++)
                {
                    DataRow dRow = dt.Rows[iRow];

                    getRowForEdit(ref dsInputInfo, ref dr, "p_workflow_rules", iRow);

                    string s_AF_ROW_ID = "";
                    if (IsEdit)
                        s_AF_ROW_ID = dRow["af_row_id"].ToString();
                    else
                        s_AF_ROW_ID = getHashKey();

                    dr["af_row_id"] = s_AF_ROW_ID;
                    dr["name"] = dRow["RuleName"];
                    if (dr.Table.Columns.Contains("Target"))
                        dr["Target"] = dRow["Target"];
                    string sSource = "";
                    string sTarget = "";
                    if (ddlbased_on.Text.ToLower() == "title")
                    {
                        sSource = getColumnValue("sy_org_structure", "title", dRow["SourceTitle"].ToString(), "af_row_id");
                    }
                    else if (ddlbased_on.Text.ToLower() == "user")
                    {
                        sSource = getColumnValue("sy_usr", "user_id", dRow["SourceTitle"].ToString(), "af_row_id");
                    }

                    dr["source_title"] = sSource;//afrowid

                    if (dRow["Target"].ToString().ToLower() == "title")
                    {
                        sTarget = getColumnValue("sy_org_structure", "title", dRow["TargetTitle"].ToString(), "af_row_id");
                    }
                    else if (dRow["Target"].ToString().ToLower() == "user")
                    {

                        sTarget = getColumnValue("sy_usr", "user_id", dRow["TargetTitle"].ToString(), "af_row_id");
                    }
                    else if (dRow["Target"].ToString().ToLower() == "user_from_field")
                    {
                        HDDatabase HDD = new HDDatabase();
                        String sSql = "select af_row_id from sy_obj_att where object_id='" + ddObject.SelectedValue + "' and attrib_id='" + dRow["TargetTitle"].ToString() + "'";
                        string sTemp = HDD.GetColumnValue(sSql);
                        sTarget = sTemp;
                        HDD = null; //sTarget = dRow["TargetTitle"].ToString();
                    }

                    dr["target_title"] = sTarget;//afrowid
                    dr["sequence"] = iRow;
                    dr["ruleset"] = hf_ruleset_af_row_id.Value;
                    fillDefaultColumns(ref dr, sCurrentDate);
                    if (!IsEdit || dr.RowState == DataRowState.Detached)
                        dsInputInfo.Tables["p_workflow_rules"].Rows.Add(dr);
                    dr = null;

                    if (dsInputInfo.Tables["p_work_item"] != null)
                    {
                        getRowForEdit(ref dsInputInfo, ref dr, "p_work_item", iRow);

                        dr["title"] = dRow["RuleName"];
                        dr["message"] = dRow["WI_Message"];
                        dr["Rule_ID"] = s_AF_ROW_ID;
                        fillDefaultColumns(ref dr, sCurrentDate);
                        if (!IsEdit || dr.RowState == DataRowState.Detached)
                        {
                            dr["af_row_id"] = getHashKey();
                            dsInputInfo.Tables["p_work_item"].Rows.Add(dr);
                        }
                        dr = null;
                    }

                    //if (dRow["addFieldUpdate"].ToString().ToLower() == "true")
                    //{
                    if (dsInputInfo.Tables["p_field_updates"] != null)
                    {
                        getRowForEdit(ref dsInputInfo, ref dr, "p_field_updates", iRow);

                        if (dRow["addFieldUpdate"].ToString().ToLower() == "true")
                        {
                            dr["field_name"] = dRow["FieldUpdateField"];
                            dr["field_value"] = dRow["FieldUpdateValue"];
                            dr["Rule_ID"] = s_AF_ROW_ID;
                        }
                        else
                        {
                            dr["field_name"] = System.DBNull.Value;
                            dr["field_value"] = System.DBNull.Value;
                            dr["Rule_ID"] = s_AF_ROW_ID;
                        }

                        fillDefaultColumns(ref dr, sCurrentDate);
                        if (!IsEdit || dr.RowState == DataRowState.Detached)
                        {
                            dr["af_row_id"] = getHashKey();
                            dsInputInfo.Tables["p_field_updates"].Rows.Add(dr);
                        }
                        dr = null;
                    }
                    //}

                    //if (dRow["addFieldUpdateReject"].ToString().ToLower() == "true")
                    //{
                    if (dsInputInfo.Tables["p_reject_field_updates"] != null)
                    {
                        getRowForEdit(ref dsInputInfo, ref dr, "p_reject_field_updates", iRow);

                        if (dRow["addFieldUpdateReject"].ToString().ToLower() == "true")
                        {
                            dr["field_name"] = dRow["FieldUpdateFieldReject"];
                            dr["field_value"] = dRow["FieldUpdateValueReject"];
                            dr["Rule_ID"] = s_AF_ROW_ID;
                        }
                        else
                        {
                            dr["field_name"] = System.DBNull.Value;
                            dr["field_value"] = System.DBNull.Value;
                            dr["Rule_ID"] = s_AF_ROW_ID;
                        }

                        fillDefaultColumns(ref dr, sCurrentDate);
                        if (!IsEdit || dr.RowState == DataRowState.Detached)
                        {
                            dr["af_row_id"] = getHashKey();
                            dsInputInfo.Tables["p_reject_field_updates"].Rows.Add(dr);
                        }
                        dr = null;
                    }
                    //}
                    //Added by John Sathish
                    if (dsInputInfo.Tables["p_workflow_action"] != null)
                    {
                        getRowForEdit(ref dsInputInfo, ref dr, "p_workflow_action", iRow); //+ddObject.SelectedValue + "' and attrib_id='" + dRow["TargetTitle"].ToString() + "'";

                        if (dr["af_row_id"].ToString() == "")
                        {
                            if (dRow["addFieldEmail"].ToString().ToLower() == "true")
                            {
                                dr["action_type"] = "SE";
                                dr["action_event"] = "OA";
                                HDDatabase HDD = new HDDatabase();
                                String sSql = "select af_row_id from sy_email_template where name='" + ddlAppEmail.SelectedValue + "'";// and action_event='OA'";
                                dr["parameter"] = HDD.GetColumnValue(sSql);
                                dr["Rule_ID"] = s_AF_ROW_ID;
                            }
                        }
                        else
                        {
                            if (dr["action_event"].ToString() == "OA")
                            {
                                if (dRow["addFieldEmail"].ToString().ToLower() == "true")
                                {
                                    dr["action_type"] = "SE";
                                    dr["action_event"] = "OA";
                                    HDDatabase HDD = new HDDatabase();
                                    String sSql = "select af_row_id from sy_email_template where name='" + ddlAppEmail.SelectedValue + "'";// and action_event='OA'";
                                    dr["parameter"] = HDD.GetColumnValue(sSql);
                                    dr["Rule_ID"] = s_AF_ROW_ID;
                                }
                            }
                            else if (dr["action_event"].ToString() == "OR")
                            {
                                if (dRow["addFieldEmailRej"].ToString().ToLower() == "true")
                                {
                                    dr["action_type"] = "SE";
                                    dr["action_event"] = "OR";
                                    HDDatabase HDD = new HDDatabase();
                                    String sSql = "select af_row_id from sy_email_template where name='" + ddlRejEmail.SelectedValue + "'";// and action_event='OR'";
                                    dr["parameter"] = HDD.GetColumnValue(sSql);
                                    dr["Rule_ID"] = s_AF_ROW_ID;
                                }
                            }
                        }
                        fillDefaultColumns(ref dr, sCurrentDate);
                        if (!IsEdit || dr.RowState == DataRowState.Detached)
                        {
                            dr["af_row_id"] = getHashKey();
                            dsInputInfo.Tables["p_workflow_action"].Rows.Add(dr);
                        }
                        dr = null;
                    }

                    if (dsInputInfo.Tables["p_workflow_action"] != null)
                    {
                        getRowForEdit(ref dsInputInfo, ref dr, "p_workflow_action", iRow + 1);

                        if (dr["af_row_id"].ToString() == "")
                        {
                            if (dRow["addFieldEmailRej"].ToString().ToLower() == "true")
                            {
                                dr["action_type"] = "SE";
                                dr["action_event"] = "OR";
                                HDDatabase HDD = new HDDatabase();
                                String sSql = "select af_row_id from sy_email_template where name='" + ddlRejEmail.SelectedValue + "'";// and action_event='OR'";
                                dr["parameter"] = HDD.GetColumnValue(sSql);
                                dr["Rule_ID"] = s_AF_ROW_ID;
                            }
                        }
                        else
                        {
                            if (dr["action_event"].ToString() == "OA")
                            {
                                if (dRow["addFieldEmail"].ToString().ToLower() == "true")
                                {
                                    dr["action_type"] = "SE";
                                    dr["action_event"] = "OA";
                                    HDDatabase HDD = new HDDatabase();
                                    String sSql = "select af_row_id from sy_email_template where name='" + ddlAppEmail.SelectedValue + "'";// and action_event='OA'";
                                    dr["parameter"] = HDD.GetColumnValue(sSql);
                                    dr["Rule_ID"] = s_AF_ROW_ID;
                                }
                            }
                            else if (dr["action_event"].ToString() == "OR")
                            {
                                if (dRow["addFieldEmailRej"].ToString().ToLower() == "true")
                                {
                                    dr["action_type"] = "SE";
                                    dr["action_event"] = "OR";
                                    HDDatabase HDD = new HDDatabase();
                                    String sSql = "select af_row_id from sy_email_template where name='" + ddlRejEmail.SelectedValue + "'";// and action_event='OR'";
                                    dr["parameter"] = HDD.GetColumnValue(sSql);
                                    dr["Rule_ID"] = s_AF_ROW_ID;
                                }
                            }
                        }
                        fillDefaultColumns(ref dr, sCurrentDate);
                        if (!IsEdit || dr.RowState == DataRowState.Detached)
                        {
                            dr["af_row_id"] = getHashKey();
                            dsInputInfo.Tables["p_workflow_action"].Rows.Add(dr);
                        }
                        dr = null;
                    }
                    //Up to this
                }
                dt = null;
                IsEdit = true;
            }


            // Added by srivatsan for workitem additional info
            if (dsInputInfo.Tables["p_workitem_additional_info"] != null)
            {
                string curruserid = Session["user_afrowid"].ToString();//Session["userid"].ToString();
                HDDatabase hddadd = new HDDatabase();
                DataTable datatable = dsInputInfo.Tables["p_workitem_additional_info"];
                DataRow dr1 = null;
                string[] deleteitems = new string[chkboxAdditionalFields.Items.Count];
                string[] deleteitemsafrowid = new string[chkboxAdditionalFields.Items.Count];

                for (int i = 0; i < chkboxAdditionalFields.Items.Count; i++)
                {
                    if (chkboxAdditionalFields.Items[i].Selected == true)
                    {

                        DataRow[] drselect = dsInputInfo.Tables["p_workitem_additional_info"].Select("attrib_id='" + chkboxAdditionalFields.Items[i].Value + "' and ruleset_id = '" + hf_ruleset_af_row_id.Value + "'");
                        if (drselect.Length > 0)
                        {
                            getRowForEdit(ref dsInputInfo, ref dr1, "p_workitem_additional_info", i);
                            if (Request.QueryString["PK"] != null)
                            {
                                string rulesetid = Request.QueryString["PK"].ToString();
                                dr1["af_row_id"] = dr1["af_row_id"].ToString();
                                dr1["ruleset_id"] = rulesetid;
                                dr1["attrib_id"] = dr1["attrib_id"].ToString();
                                dr1["object_id"] = dr1["object_id"].ToString();
                                //dr1["seq"] = dr1["seq"].ToString();
                                dr1["seq"] = i;
                            }
                        }
                        else
                        {
                            try
                            {
                                dr1 = datatable.NewRow();
                                dr1["af_row_id"] = getHashKey();
                                dr1["ruleset_id"] = hf_ruleset_af_row_id.Value;
                                dr1["attrib_id"] = chkboxAdditionalFields.Items[i].Value;
                                dr1["object_id"] = ddObject.SelectedValue;
                                dr1["seq"] = i;

                                dsInputInfo.Tables["p_workitem_additional_info"].Rows.Add(dr1);
                            }
                            catch (Exception ex)
                            {
                                LogWriter.WriteLog(ex.Message);
                            }

                        }
                    }
                    else
                    {
                        deleteitems[i] = chkboxAdditionalFields.Items[i].Value;
                        DataRow[] mydeleterow = dsInputInfo.Tables["p_workitem_additional_info"].Select("attrib_id ='" + deleteitems[i] + "'");
                        if (mydeleterow.Length > 0)
                        {
                            string af_row_id = mydeleterow[0]["af_row_id"].ToString();
                            deleteitemsafrowid[i] = af_row_id;
                        }

                    }

                }




                Master objmaster = new Master();
                try
                {
                    deleteAdditionalFields(objmaster, deleteitemsafrowid);
                }
                catch (Exception ex)
                {
                    LogWriter.WriteLog("Error delete additional Info" + ex.Message);
                }
                finally
                {
                    objmaster = null;
                }

                dr = null;
            }



        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("fillPageData : Error : " + ex.Message);
        }
    }

    protected void btnSave_ServerClick(object sender, EventArgs e)
    {
        try
        {
            collectWorkFlowRules();
            if (loadRules())
            {
                if (!validate()) return;
                DataSet dsPageInfo = getPagesetInfo();
                DataSet dsInputInfo = getDataset(dsPageInfo);
                fillPageData(ref dsInputInfo);

                //added by Sampath on 10-Nov-2011 for Encoding
                //CommonFunctions.encodeData(dsInputInfo);

                Master objMaster = new Master();
                if (objMaster.ProcessOperation(dsPageInfo, dsInputInfo, "INSERT"))
                {
                    Session["dtWorkflow"] = null;
                    Response.Redirect(hfRequestURL.Value);
                }
                else
                    lbl_message.Text = wrapItAsMessage(objMaster.ErrorMessage, true);
                dsPageInfo = null;
                dsInputInfo = null;
                objMaster = null;
            }
            else
                lblstatus.Text = wrapItAsMessage("At least one rule is mandatory to create a Ruleset.", true);
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("btnSave_ServerClick : Error : " + ex.Message);
        }
    }

    private string wrapItAsMessage(string msg, bool isError)
    {
        return "<div class=\"" + (isError == true ? "mbErrorMessage" : "mbMessage") + "\">" + msg + "</div>";
    }

    private void getDatasetIU(ref DataSet dsInputInfo, ref DataSet dsInsert, ref DataSet dsUpdate)
    {
        try
        {
            foreach (DataTable dt in dsInputInfo.Tables)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    if (dr.RowState == DataRowState.Added)
                        dsInsert.Tables[dt.TableName].ImportRow(dr);
                    else if (dr.RowState == DataRowState.Modified)
                        dsUpdate.Tables[dt.TableName].ImportRow(dr);
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getDatasetIU : Error : " + ex.Message);
        }
    }

    private bool deleteRules(Master objMaster)
    {
        try
        {
            PageInfoLoad objPIL = new PageInfoLoad();
            DataSet dsPageInfo = objPIL.GetPageSetPageCtrlInfo("eb23d3fcf5911d62"); // workflow_rules

            foreach (ListItem li in lstDeletedRules.Items)
            {
                if (!objMaster.ProcessOperation(dsPageInfo, li.Text, "DELETE"))
                {
                    lbl_message.Text = wrapItAsMessage(objMaster.ErrorMessage, true);
                    return false;
                }
            }

            dsPageInfo = objPIL.GetPageSetPageCtrlInfo("f50abe7653ed667a"); // workflow_triggers
            objPIL = null;

            foreach (ListItem li in lstResetTriggers.Items)
            {
                if (!objMaster.ProcessOperation(dsPageInfo, li.Text, "DELETE"))
                {
                    lbl_message.Text = wrapItAsMessage(objMaster.ErrorMessage, true);
                    return false;
                }
            }
            lstDeletedRules.Items.Clear();
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("deleteRules : Error : " + ex.Message);
        }
        return true;
    }

    protected void btnUpdate_ServerClick(object sender, EventArgs e)
    {
        try
        {
            collectWorkFlowRules();
            if (loadRules())
            {
                if (!validate()) return;
                DataSet dsPageInfo = getPagesetInfo();
                DataSet dsInputInfo = new DataSet();
                fillPageData(ref dsInputInfo);

                //added by Sampath on 10-Nov-2011 for Encoding
                //CommonFunctions.encodeData(dsInputInfo);

                GlobalValues.dsAudit = dsInputInfo;
                DataSet dsInsert = dsInputInfo.Clone();
                DataSet dsUpdate = dsInputInfo.Clone();
                getDatasetIU(ref dsInputInfo, ref dsInsert, ref dsUpdate);

                Master objMaster = new Master();
                if (deleteRules(objMaster))
                {
                    objMaster.DeleteMessage = "";
                    if (objMaster.ProcessOperation(dsPageInfo, dsUpdate, "UPDATE"))
                    {
                        if (objMaster.ProcessOperation(dsPageInfo, dsInsert, "INSERT"))
                        {
                            Session["dtWorkflow"] = null;
                            Response.Redirect(hfRequestURL.Value);
                        }
                        else
                            lbl_message.Text = wrapItAsMessage(objMaster.ErrorMessage, true);
                    }
                    else
                        lbl_message.Text = wrapItAsMessage(objMaster.ErrorMessage, true);
                }
                GlobalValues.dsAudit = null;
                dsPageInfo = null;
                dsInputInfo = null;
                dsInsert = null;
                dsUpdate = null;
                objMaster = null;
            }
            else
                lblstatus.Text = wrapItAsMessage("At least one rule is mandatory to create a Ruleset.", true);
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("btnUpdate_ServerClick : Error : " + ex.Message);
        }
    }

    protected void btnReset_ServerClick(object sender, EventArgs e)
    {
        try
        {
            if (Request.QueryString["PK"] == null)
                Session["dtWorkflow"] = null;

            string strPagesetRowID = Request.QueryString["pgs_id"].ToString();
            string strMenuRowId = Request.QueryString["mn"].ToString();
            //added for static page list view AddNew
            HDDatabase HDD = new HDDatabase();
            GenerateGrid objGD = new GenerateGrid();
            string sEditPage = objGD.getEditPage(HDD, strMenuRowId);
            //
            string strPageUrl = sEditPage + "?pgs_id=" + strPagesetRowID + "&mn=" + strMenuRowId;

            if (Request.QueryString["PK"] != null)
                strPageUrl = strPageUrl + "&PK=" + Request.QueryString["PK"];
            if (IsCopy)
                strPageUrl += "&CPY=0";
            Response.Redirect(strPageUrl);
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("btnReset_ServerClick : Error : " + ex.Message);
        }
    }

    private ArrayList getDefaultColumns()
    {
        ArrayList alDefaultCols = new ArrayList();

        try
        {
            HDDatabase HDD = new HDDatabase();
            string sSql = "select * from sy_acr_mem where acr_id='cee69885ce44589c' order by mem_seq";
            DataTable dtDef = HDD.GetDataTable(sSql);
            alDefaultCols.Add("af_row_id");
            foreach (DataRow dr in dtDef.Rows)
            {
                alDefaultCols.Add(dr["mem_id"].ToString());
            }
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("getDefaultColumns : Error : " + ex.Message);
        }
        return alDefaultCols;
    }

    protected void ddObject_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            //Session["dtWorkflow"] = null;
            deleteRulesIfEdit();
            ddField1.Items.Clear();
            ddField2.Items.Clear();
            ddField3.Items.Clear();
            ddField4.Items.Clear();
            ddField5.Items.Clear();
            ddFieldsUpdate.Items.Clear();
            ddFieldsUpdateReject.Items.Clear();
            string objId = ddObject.SelectedValue;
            ddOperator1.SelectedValue = "";
            ddOperator2.SelectedValue = "";
            ddOperator3.SelectedValue = "";
            ddOperator4.SelectedValue = "";
            ddOperator5.SelectedValue = "";
            ddand_or1.SelectedValue = "AND";
            ddand_or2.SelectedValue = "AND";
            ddand_or3.SelectedValue = "AND";
            ddand_or4.SelectedValue = "AND";
            txtValue1.Text = "";
            txtValue2.Text = "";
            txtValue3.Text = "";
            txtValue4.Text = "";
            txtValue5.Text = "";
            ddField1.Items.Add(new ListItem("--None--", ""));
            ddField2.Items.Add(new ListItem("--None--", ""));
            ddField3.Items.Add(new ListItem("--None--", ""));
            ddField4.Items.Add(new ListItem("--None--", ""));
            ddField5.Items.Add(new ListItem("--None--", ""));
            //ddSkipField.Items.Add(new ListItem("--None--", ""));
            ddFieldsUpdate.Items.Add(new ListItem("--None--", ""));
            ddFieldsUpdateReject.Items.Add(new ListItem("--None--", ""));

            if (objId.Length > 0)
            {

                fillchkboxAdditionalFields(); // Added by srivatsan

                HDDatabase hdd = new HDDatabase();
                DataSet ds = hdd.GetDataset("select attrib_id,attrib_name from sy_obj_att where object_id='" + objId + "' order by attrib_name asc");
                if (ds.Tables.Count > 0)
                {
                    string sTemp = "";// "<OPTION SELECTED>Select a field</OPTION>";
                    foreach (DataRow dr in ds.Tables[0].Select("", "attrib_name asc"))
                    {
                        if (dr["attrib_id"].ToString() != "af_row_id")
                            sTemp += dr["attrib_id"].ToString() + ",";//"<OPTION>" + dr["attrib_id"].ToString() + "</OPTION>";
                        if (!arDef.Contains(dr["attrib_id"].ToString()))
                        {
                            ddField1.Items.Add(new ListItem(dr["attrib_name"].ToString(), dr["attrib_id"].ToString()));
                            ddField2.Items.Add(new ListItem(dr["attrib_name"].ToString(), dr["attrib_id"].ToString()));
                            ddField3.Items.Add(new ListItem(dr["attrib_name"].ToString(), dr["attrib_id"].ToString()));
                            ddField4.Items.Add(new ListItem(dr["attrib_name"].ToString(), dr["attrib_id"].ToString()));
                            ddField5.Items.Add(new ListItem(dr["attrib_name"].ToString(), dr["attrib_id"].ToString()));
                            ddFieldsUpdate.Items.Add(new ListItem(dr["attrib_name"].ToString(), dr["attrib_id"].ToString()));
                            ddFieldsUpdateReject.Items.Add(new ListItem(dr["attrib_name"].ToString(), dr["attrib_id"].ToString()));
                        }
                    }
                    hf_Field.Value = sTemp;
                }
                hdd = null;
            }
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("ddObject_SelectedIndexChanged : Error : " + ex.Message);
        }
    }

    private void getAllFields(string Object_Id)
    {
        try
        {
            //Session["dtWorkflow"] = null;
            ddField1.Items.Clear();
            ddField2.Items.Clear();
            ddField3.Items.Clear();
            ddField4.Items.Clear();
            ddField5.Items.Clear();
            ddFieldsUpdate.Items.Clear();
            ddFieldsUpdateReject.Items.Clear();
            string objId = Object_Id;
            ddField1.Items.Add(new ListItem("--None--", ""));
            ddField2.Items.Add(new ListItem("--None--", ""));
            ddField3.Items.Add(new ListItem("--None--", ""));
            ddField4.Items.Add(new ListItem("--None--", ""));
            ddField5.Items.Add(new ListItem("--None--", ""));
            //ddSkipField.Items.Add(new ListItem("--None--", ""));
            ddFieldsUpdate.Items.Add(new ListItem("--None--", ""));
            ddFieldsUpdateReject.Items.Add(new ListItem("--None--", ""));
            if (objId.Length > 0)
            {
                string sTemp = "";
                HDDatabase hdd = new HDDatabase();
                DataSet ds = hdd.GetDataset("select attrib_id,attrib_name from sy_obj_att where object_id='" + objId + "'");
                if (ds.Tables.Count > 0)
                {
                    foreach (DataRow dr in ds.Tables[0].Select("", "attrib_name asc"))
                    {
                        if (!arDef.Contains(dr["attrib_id"].ToString()))
                        {
                            ddField1.Items.Add(new ListItem(dr["attrib_name"].ToString(), dr["attrib_id"].ToString()));
                            ddField2.Items.Add(new ListItem(dr["attrib_name"].ToString(), dr["attrib_id"].ToString()));
                            ddField3.Items.Add(new ListItem(dr["attrib_name"].ToString(), dr["attrib_id"].ToString()));
                            ddField4.Items.Add(new ListItem(dr["attrib_name"].ToString(), dr["attrib_id"].ToString()));
                            ddField5.Items.Add(new ListItem(dr["attrib_name"].ToString(), dr["attrib_id"].ToString()));
                            ddFieldsUpdate.Items.Add(new ListItem(dr["attrib_name"].ToString(), dr["attrib_id"].ToString()));
                            ddFieldsUpdateReject.Items.Add(new ListItem(dr["attrib_name"].ToString(), dr["attrib_id"].ToString()));
                        }
                        if (dr["attrib_id"].ToString().ToLower() != "af_row_id")
                            sTemp += dr["attrib_id"].ToString() + ",";
                    }
                    hf_Field.Value = sTemp;
                }
                hdd = null;
            }
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("getAllFields : Error : " + ex.Message);
        }
    }

    private string getHashKey()
    {
        string ret = "";
        ScreenReader sr = new ScreenReader();
        ret = sr.getHashKey();
        sr = null;
        return ret;
    }

    private DataTable createDataTable4Workflow()
    {
        DataTable dt = new DataTable();
        dt.TableName = "WorkflowRules";

        for (int i = 0; i < cols.Length; i++)
            dt.Columns.Add(new DataColumn(cols[i], "ss".GetType()));
        return dt;
    }

    protected void btnRuleUpdate_Click(object sender, EventArgs e)
    {
        try
        {
            collectWorkFlowRules();
            //"af_row_id", "RuleName", "SourceTitle", "TargetTitle", "AddWorkItem", "WI_Message", "addFieldUpdate", "FieldUpdateField", "FieldUpdateValue"
            DataTable dt = new DataTable();
            if (Session["dtWorkflow"] == null)
                dt = createDataTable4Workflow();
            else
                dt = (DataTable)Session["dtWorkflow"];
            DataRow[] drs = dt.Select("af_row_id='" + hfRule_Af_row_id.Value + "'");
            DataRow dr = drs[0];
            dr["af_row_id"] = hfRule_Af_row_id.Value;
            dr["RuleName"] = txtRuleName.Text;
            dr["Target"] = hf_Target.Value;
            if (ddlbased_on.Text.ToLower() == "title")
            {
                dr["SourceTitle"] = ddlSourceTitle.Text;
                dr["TargetTitle"] = hf_TargetSelected.Value;// ddlTargetTitle.Text;
            }
            else
            {
                dr["SourceTitle"] = ddlSourceUser.Text;
                dr["TargetTitle"] = hf_TargetSelected.Value;// ddlTargetUser.Text;
            }
            //dr["SourceTitle"] = txtSourceTitle.Text;
            //dr["TargetTitle"] = txtTargetTitle.Text;
            dr["AddWorkItem"] = chkAddWI.Checked.ToString();
            dr["WI_Message"] = txtWI_Message.Text;
            dr["addFieldUpdate"] = chkFieldUpdate.Checked.ToString();
            dr["FieldUpdateField"] = ddFieldsUpdate.SelectedValue;
            dr["FieldUpdateValue"] = txtFieldValue.Text;
            dr["addFieldUpdateReject"] = chkFieldUpdateReject.Checked.ToString();
            dr["FieldUpdateFieldReject"] = ddFieldsUpdateReject.SelectedValue;
            dr["FieldUpdateValueReject"] = txtFieldValueReject.Text;
            //Added by John Sathish
            dr["addFieldEmail"] = cbxAppEmail.Checked.ToString();
            dr["FieldEmailTemplate"] = ddlAppEmail.SelectedValue;
            dr["addFieldEmailRej"] = cbxRejEmail.Checked.ToString();
            dr["FieldEmailTemplateRej"] = ddlRejEmail.SelectedValue;
            //Up to this
            //dt.Rows.Add(dr);
            dt.AcceptChanges();

            Session["dtWorkflow"] = dt;
            lblstatus.Text = "";
            showRulesOnTable(dt);
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("btnRuleUpdate_Click : Error : " + ex.Message);
        }
    }

    private void destroyControls()
    {
        try
        {

            for (int iCount = 1; iCount < tblRules.Rows.Count; iCount++)
                for (int iiCount = 0; iiCount < tblRules.Rows[iCount].Cells.Count; iiCount++)
                    tblRules.Rows[iCount].Cells[iiCount].Controls.Clear();
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("showRulesOnTable : Error : " + ex.Message);
        }
    }

    private void addHeader()
    {
        tblRules.Rows.Clear();
        TableRow tr = new TableRow();
        TableCell tc = new TableCell();
        tc.Text = "";
        tr.Cells.Add(tc);
        tc = new TableCell();
        tc.Text = "Rule Name";
        tr.Cells.Add(tc);
        tc = new TableCell();
        tc.Text = "Source Title";
        tr.Cells.Add(tc);
        tc = new TableCell();
        tc.Text = "Target Title";
        tr.Cells.Add(tc);
        tc = new TableCell();
        tc.Text = "";
        tr.Cells.Add(tc);
        tc = new TableCell();
        tc.Text = "";
        tr.Cells.Add(tc);
        tr.CssClass = "Grid_Header";
        tblRules.Rows.Add(tr);
    }

    private void showRulesOnTable(DataTable dt)
    {
        try
        {
            if (dt == null) return;
            int rowCount = 0;
            int iClass = 0;
            int classNum = 0;
            //tblRules.Controls.Clear();
            //destroyControls();
            tblRules.BorderStyle = BorderStyle.Solid;
            //addHeader();
            foreach (DataRow dr in dt.Rows)
            {
                TableRow tr = new TableRow();
                //tr.ID = "tr_" + rowCount.ToString();
                TableCell tc = new TableCell();

                for (int i = 0; i < cols.Length; i++)
                {
                    switch (cols[i])
                    {
                        case "af_row_id":
                        case "AddWorkItem":
                        case "WI_Message":
                        case "addFieldUpdate":
                        case "FieldUpdateField":
                        case "FieldUpdateValue":
                        case "addFieldUpdateReject":
                        case "FieldUpdateFieldReject":
                        case "FieldUpdateValueReject":
                        //Added by John Sathish
                        case "addFieldEmail":
                        case "FieldEmailTemplate":
                        case "addFieldEmailRej":
                        case "FieldEmailTemplateRej":
                        //up to this
                        case "Target":
                            HiddenField hf = new HiddenField();
                            hf.ID = cols[i] + rowCount.ToString();
                            hf.Value = dr[cols[i]].ToString();
                            tblRules.Rows[0].Cells[4].Controls.Add(hf);
                            break;
                        case "RuleName":
                        case "SourceTitle":
                        case "TargetTitle":
                            hf = new HiddenField();
                            hf.ID = "hf_" + cols[i] + rowCount.ToString();
                            hf.Value = dr[cols[i]].ToString();
                            tblRules.Rows[0].Cells[4].Controls.Add(hf);
                            if (lstDeletedRules.Items.FindByText(dr["af_row_id"].ToString()) == null)//if (Request.Form["ctl00$ContentPlaceHolder3$af_row_id" + rowCount.ToString()] != hfRule_delete.Value)
                            {
                                Label l = new Label();
                                if (cols[i] == "RuleName")
                                {
                                    l.ID = "ruleSeq" + rowCount.ToString();
                                    l.Text = Convert.ToString(iClass + 1);
                                    tc = new TableCell();
                                    tc.HorizontalAlign = HorizontalAlign.Center;
                                    tc.Controls.Add(l);
                                    tr.Cells.Add(tc);
                                }
                                l = new Label();
                                l.ID = cols[i] + rowCount.ToString();
                                l.Text = dr[cols[i]].ToString();
                                tc = new TableCell();
                                tc.Controls.Add(l);
                                tr.Cells.Add(tc);
                            }
                            break;
                    }
                }
                if (lstDeletedRules.Items.FindByText(dr["af_row_id"].ToString()) == null)//if (Request.Form["ctl00$ContentPlaceHolder3$af_row_id" + rowCount.ToString()] != hfRule_delete.Value)
                {
                    if (HttpContext.Current.Request.QueryString["VMODE"] == null)
                    {
                        tc = new TableCell();
                        ImageButton ib = new ImageButton();
                        ib.ID = "edit" + rowCount.ToString();
                        ib.ImageUrl = "images/edit_wizard.gif";//images/edit_wizard.gif
                        ib.ToolTip = "Edit";
                        ib.OnClientClick = "javascript:EditRules('" + dr["af_row_id"].ToString() + "','" + rowCount.ToString() + "');return false;";
                        //ib.Attributes.Add("onclick", "EditRules('" + dr["af_row_id"].ToString() + "','" + rowCount.ToString() + "');return false;");
                        tc.Controls.Add(ib);
                        tc.Width = 25;
                        tr.Cells.Add(tc);

                        tc = new TableCell();
                        ib = new ImageButton();
                        ib.ID = "delete" + rowCount.ToString();
                        ib.ImageUrl = "images/delete.gif";//images/edit_wizard.gif
                        ib.ToolTip = "Delete";
                        ib.OnClientClick = "javascript:return DeleteRules('" + dr["RuleName"].ToString() + "','" + dr["af_row_id"].ToString() + "')";
                        //ib.Click += new ImageClickEventHandler(deleteRule_Click);            
                        //ib.Click += new EventHandler(deleteRule_Click);
                        //ib.Attributes.Add("onclick", "DeleteRules('" + dr["RuleName"].ToString() + "')");

                        tc.Controls.Add(ib);
                        tc.Width = 25;
                        tc.EnableViewState = true;
                        classNum = iClass % 2;
                        iClass++;
                        tr.Cells.Add(tc);
                    }
                }
                //int classNum = rowCount % 2;
                rowCount++;

                if (Request.QueryString["VMODE"] != null)
                    if (Request.QueryString["VMODE"].ToString() == "1")
                        iClass++;

                tr.Attributes.Add("Class", "Grid_Row" + classNum.ToString());
                tr.EnableViewState = true;
                tblRules.Rows.Add(tr);
            }
            hf_RowCount.Value = rowCount.ToString();
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("showRulesOnTable : Error : " + ex.Message);
        }
    }

    void deleteRule_Click(object sender, ImageClickEventArgs e)
    {
        deleteRule_Click();
    }

    void deleteRule_Click()
    {
        try
        {
            if (hfRule_delete.Value == "") return;
            collectWorkFlowRules();
            DataTable dt = new DataTable();
            //if (Session["dtWorkflow"] == null)
            //dt = createDataTable4Workflow();
            //else
            dt = (DataTable)Session["dtWorkflow"];

            //DataRow[] drs = dt.Select("af_row_id='" + hfRule_delete.Value + "'");
            lstDeletedRules.Items.Add(hfRule_delete.Value);
            //DataRow dr = drs[0];
            //dt.Rows.Remove(dr);
            //dt.AcceptChanges();
            //hfRule_delete.Value = "";
            Session["dtWorkflow"] = dt;

            showRulesOnTable(dt);
            hfRule_delete.Value = "";
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("deleteRule_Click : Error : " + ex.Message);
        }
    }

    protected void btnRuleSave_Click(object sender, EventArgs e)
    {
        try
        {
            collectWorkFlowRules();
            //"af_row_id", "RuleName", "SourceTitle", "TargetTitle", "AddWorkItem", "WI_Message", "addFieldUpdate", "FieldUpdateField", "FieldUpdateValue"
            DataTable dt = new DataTable();
            if (Session["dtWorkflow"] == null)
                dt = createDataTable4Workflow();
            else
                dt = (DataTable)Session["dtWorkflow"];
            DataRow dr = dt.NewRow();
            dr["af_row_id"] = getHashKey();
            //dr["Sequence"] = dt.Rows.Count + 1;
            dr["RuleName"] = txtRuleName.Text;

            dr["Target"] = hf_Target.Value;
            if (ddlbased_on.Text.ToLower() == "title")
            {
                dr["SourceTitle"] = ddlSourceTitle.Text;
                dr["TargetTitle"] = hf_TargetSelected.Value;// ddlTargetTitle.Text;
            }
            else
            {
                dr["SourceTitle"] = ddlSourceUser.Text;
                dr["TargetTitle"] = hf_TargetSelected.Value;// ddlTargetUser.Text;
            }

            dr["AddWorkItem"] = chkAddWI.Checked.ToString();
            dr["WI_Message"] = txtWI_Message.Text; ;
            dr["addFieldUpdate"] = chkFieldUpdate.Checked.ToString();
            dr["FieldUpdateField"] = ddFieldsUpdate.SelectedValue;
            dr["FieldUpdateValue"] = txtFieldValue.Text;
            dr["addFieldUpdateReject"] = chkFieldUpdateReject.Checked.ToString();
            dr["FieldUpdateFieldReject"] = ddFieldsUpdateReject.SelectedValue;
            dr["FieldUpdateValueReject"] = txtFieldValueReject.Text;
            //Added by John Sathish
            dr["addFieldEmail"] = cbxAppEmail.Checked.ToString();
            dr["FieldEmailTemplate"] = ddlAppEmail.SelectedValue;
            dr["addFieldEmailRej"] = cbxRejEmail.Checked.ToString();
            dr["FieldEmailTemplateRej"] = ddlRejEmail.SelectedValue;
            //Up to this
            dt.Rows.Add(dr);

            Session["dtWorkflow"] = dt;
            lblstatus.Text = "";
            showRulesOnTable(dt);
        }


        catch (Exception ex)
        {
            LogWriter.WriteLog("btnRuleSave_Click : Error : " + ex.Message);
        }
    }

    protected void btnRuleSaveUpdate_Click(object sender, EventArgs e)
    {
        if (hfRule_Af_row_id.Value == "")
            btnRuleSave_Click(sender, e);
        else
            btnRuleUpdate_Click(sender, e);
    }

    private void deleteRulesIfEdit()
    {
        //if (Request.QueryString["PK"] != null)
        //{
        try
        {
            DataTable dt = (DataTable)Session["dtWorkflow"];
            if (dt != null)
            {
                DataTable dtTemp = dt.Clone();
                foreach (DataRow dr in dt.Rows)
                {
                    if ((dr["addFieldUpdate"].ToString().ToLower() == "false" && dr["FieldUpdateField"].ToString().ToLower() == "") && (dr["addFieldUpdateReject"].ToString().ToLower() == "false" && dr["FieldUpdateFieldReject"].ToString().ToLower() == ""))
                    {
                        dtTemp.ImportRow(dr);
                    }
                    else
                        lstDeletedRules.Items.Add(dr["af_row_id"].ToString());
                }
                Session["dtWorkflow"] = dtTemp;
                showRulesOnTable(dtTemp);
            }
        }


        catch (Exception ex)
        {
            LogWriter.WriteLog("deleteRulesIfEdit : Error : " + ex.Message);
        }
        //}
    }

    protected void ddlbased_on_SelectedIndexChanged(object sender, EventArgs e)
    {
        resetRule();
    }

    private void resetRule()
    {
        try
        {
            if (ddlbased_on.Text.ToLower() == "title")
            {
                ddlSourceTitle.Visible = true;
                ddlTargetTitle.Visible = false; //ddlTargetTitle.Visible = true;
                ddlSourceUser.Visible = false;
                ddlTargetUser.Visible = false;
                chkSkipRule.Enabled = true;
                sourcet.Text = "Source Title";
                targett.Text = "Target Title";
                st.InnerText = "Source Title";
                tt.InnerText = "Target Title";
            }
            else if (ddlbased_on.Text.ToLower() == "user")
            {
                ddlSourceTitle.Visible = false;
                ddlTargetTitle.Visible = false;
                ddlSourceUser.Visible = true;
                ddlTargetUser.Visible = false;//ddlTargetUser.Visible = true;
                chkSkipRule.Checked = false;
                chkSkipRule.Enabled = false;
                sourcet.Text = "Source User";
                targett.Text = "Target User";
                st.InnerText = "Source User";
                tt.InnerText = "Target User";
            }

            DataTable dtRule = (DataTable)Session["dtWorkflow"];
            if (dtRule != null)
            {
                foreach (DataRow dr in dtRule.Rows)
                    lstDeletedRules.Items.Add(dr["af_row_id"].ToString());
                Session["dtWorkflow"] = null;
            }
            hf_RowCount.Value = "0";
            dtRule = null;
        }


        catch (Exception ex)
        {
            LogWriter.WriteLog("resetRule : Error : " + ex.Message);
        }
    }

    private string getColumnValue(string Tablename, string whereFieldname, string Value, string Fieldname)
    {
        string sValue = "";
        try
        {
            if (dsWorkflow.Tables.Contains(Tablename))
            {
                DataRow[] drr = dsWorkflow.Tables[Tablename].Select(whereFieldname + "='" + Value.Replace("'", "''") + "'");
                if (drr.Length > 0)
                    sValue = drr[0][Fieldname].ToString();
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("getColumnValue : Error :" + ex.Message);
        }
        return sValue;
    }

    private void collectWorkFlowRules()
    {
        try
        {
            DataTable dt = createDataTable4Workflow();
            int iTotalRows = 0;

            iTotalRows = int.Parse(hf_RowCount.Value);

            for (int iCount = 0; iCount < iTotalRows; iCount++)
            {
                //if (Request.Form["ctl00$ContentPlaceHolder3$af_row_id" + iCount.ToString()] != hfRule_delete.Value)
                //{
                DataRow dr = dt.NewRow();

                foreach (DataColumn dc in dt.Columns)
                {
                    if ("RuleName,SourceTitle,TargetTitle,".Contains(dc.ColumnName + ","))
                        dr[dc.ColumnName] = Request.Form["ctl00$ContentPlaceHolder3$hf_" + dc.ColumnName + iCount.ToString()];
                    else
                        dr[dc.ColumnName] = Request.Form["ctl00$ContentPlaceHolder3$" + dc.ColumnName + iCount.ToString()];
                }
                dt.Rows.Add(dr);
                //}
            }
            Session["dtWorkflow"] = dt;
            dt.Dispose();
            dt = null;

        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("collectWorkFlowRules : Error : " + ex.Message);
        }
    }

    private void getDataTable(ref DataSet dsInputInfo, string strPagesetRowID, string PageId)
    {
        try
        {
            DataSet dsPS = new DataSet();
            DataSet dsData = new DataSet();
            PageInfoLoad PIL = new PageInfoLoad();
            dsPS = PIL.GetPageSetPageCtrlInfo(strPagesetRowID);
            ScreenReader SR = new ScreenReader();
            SR.CreatePageDataTable(dsData, dsPS.Tables["page"], dsPS.Tables["pagectrl"]);
            SR = null;
            dsData.Tables[0].TableName = PageId;
            dsInputInfo.Tables.Add(dsData.Tables[PageId].Copy());
            dsPS.Dispose();
            dsData.Dispose();
            PIL = null;
            SR = null;
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("getDataTable : Error :" + ex.Message);
        }
    }

    private void getpageicons() // added by srivatsan for icon display
    {
        PageIcons icons = new PageIcons();
        HDDatabase HDD = new HDDatabase();
        try
        {
            string strPagesetRowId = HDD.GetColumnValue("sy_mnu", "pageset_id", "af_row_id='" + Request.QueryString["mn"].ToString() + "'");
            imgliteral.Text = "&nbsp;" + icons.geticontextfrompageset(strPagesetRowId, 2).ToString() + "&nbsp;";
            imgliteral1.Text = "&nbsp;<img src=" + icons.geticons("p_workflow_triggers", 2).ToString() + "></img>";
            imgliteral2.Text = "&nbsp;<img src=" + icons.geticons("p_workflow_rules", 2).ToString() + "></img>";

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error :getpageicons()" + ex.Message);
            imgliteral.Text = "&nbsp;<img src=" + PageIcons.strdefaulticon.ToString() + "></img>&nbsp;";
        }
        finally
        {
            HDD = null;
            icons = null;
        }
    }

    // Added by srivatsan
    public void fillchkboxAdditionalFields(string object_id)
    {
        if (object_id == "")
        {
            Panel2.Visible = false;
            lbladditionalfields.Visible = false;
            chkboxAdditionalFields.Visible = false;
        }
        else
        {
            Panel2.Visible = true;
            lbladditionalfields.Visible = true;
            chkboxAdditionalFields.Visible = true;
        }

        chkboxAdditionalFields.Items.Clear();


        HDDatabase hdd = new HDDatabase();
        DataSet ds = new DataSet();
        string getadditionalfields = "select attrib_id,attrib_name from sy_obj_att where object_id = '" + object_id + "' and attrib_id != 'af_row_id'";

        ds = hdd.GetDataset(getadditionalfields);
        if (ds != null)
        {
            if (ds.Tables[0].Rows.Count > 0)
            {
                chkboxAdditionalFields.Items.Clear();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    chkboxAdditionalFields.Items.Add(new ListItem(dr["attrib_name"].ToString(), dr["attrib_id"].ToString()));
                }
            }
        }

    }
    // Added by srivatsan
    public void fillchkboxAdditionalFields()
    {
        if (ddObject.SelectedIndex < 0 || ddObject.SelectedValue == "")
        {
            Panel2.Visible = false;
            lbladditionalfields.Visible = false;
            chkboxAdditionalFields.Visible = false;
        }
        else
        {
            Panel2.Visible = true;
            lbladditionalfields.Visible = true;
            chkboxAdditionalFields.Visible = true;



            chkboxAdditionalFields.Items.Clear();


            HDDatabase hdd = new HDDatabase();
            DataSet ds = new DataSet();

            string object_name = hdd.GetColumnValue("sy_obj", "object_id", "af_row_id='" + ddObject.SelectedValue + "'");
            string pageid = hdd.GetColumnValue("sy_pg", "af_row_id", "object_id='" + object_name + "'");


            string getadditionalfields = "select control_attrib_id,Control_name from sy_pg_ctr where page_id = '" + pageid + "' and control_attrib_id != 'af_row_id' order by Control_name";

            ds = hdd.GetDataset(getadditionalfields);
            if (ds != null)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    chkboxAdditionalFields.Items.Clear();
                    int count = 0;
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        chkboxAdditionalFields.Items.Add(new ListItem(dr["control_name"].ToString(), dr["control_attrib_id"].ToString()));
                        chkboxAdditionalFields.Items[count].Attributes.Add("sequence", count.ToString());
                        count = count + 1;
                    }
                }
            }

            if (Request.QueryString["PK"] != null)
            {
                if (Request.QueryString["VMode"] == "1")
                {
                    chkboxAdditionalFields.Enabled = false;
                }
                else
                {
                    chkboxAdditionalFields.Enabled = true;
                }
                DataSet dsadd = new DataSet();
                dsadd = hdd.GetDataset("select * from sy_workitem_additional_info where ruleset_id = '" + Request.QueryString["PK"] + "'");
                if (dsadd != null)
                {
                    if (dsadd.Tables.Count > 0)
                    {
                        if (dsadd.Tables[0].Rows.Count > 0)
                        {
                            foreach (DataRow dradd in dsadd.Tables[0].Rows)
                            {
                                try
                                {
                                    //chkboxAdditionalFields.SelectedValue = dradd["attrib_id"].ToString();
                                    chkboxAdditionalFields.Items.FindByValue(dradd["attrib_id"].ToString()).Selected = true;
                                }
                                catch
                                {

                                }
                            }
                        }
                    }
                }

            }
        }



    }

    private bool deleteAdditionalFields(Master objMaster, string[] afrowids) // Added by srivatsan
    {
        try
        {
            PageInfoLoad objPIL = new PageInfoLoad();
            DataSet dsPageInfo = objPIL.GetPageSetPageCtrlInfo("528cb5a76f032164"); // workitem_additional_info

            ////foreach (ListItem li in lstDeletedRules.Items)
            ////{
            ////    if (!objMaster.ProcessOperation(dsPageInfo, li.Text, "DELETE"))
            ////    {
            ////        lbl_message.Text = objMaster.ErrorMessage;
            ////        return false;
            ////    }
            ////}
            for (int i = 0; i < afrowids.Length; i++)
            {
                if (afrowids[i] != null)
                {
                    if (!objMaster.ProcessOperation(dsPageInfo, afrowids[i].ToString(), "DELETE"))
                    {
                        lbl_message.Text = wrapItAsMessage(objMaster.ErrorMessage, true);
                        return false;
                    }
                }
            }



        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("deleteRules : Error : " + ex.Message);
        }
        return true;
    }

    private void loadOwneridDropDown() // Added by srivatsan for owner id change
    {
        HDDatabase Hdd = new HDDatabase();
        BindControl BC = new BindControl();
        //DataSet ds = new DataSet();
        DataTable dt = null;
        try
        {
            //string bindid = Hdd.GetColumnValue("select mem_value3 from sy_acr_mem where acr_id = 'cee69885ce44589c' and mem_id = 'owner_id'");
            //BC.Bind(bindid, ddownerid, ref dt);

            //if (Session["user_afrowid"].ToString() == "e51e0327224a2eb9")
            //{
            //    ddownerid.Items.Add(new ListItem(Session["userid"].ToString(), Session["user_afrowid"].ToString()));
            //}

            if (Request.QueryString["PK"] == null)
            {
                // ddownerid.SelectedValue = Session["user_afrowid"].ToString();
                ownerid.Value = Session["user_afrowid"].ToString();
                txt_ownerid.Text = Session["userid"].ToString();
            }
            if (Request.QueryString["PK"] != null)
            {
                if (Request.QueryString["CPY"] != null)
                {
                    //ddownerid.SelectedValue = Session["user_afrowid"].ToString();
                    ownerid.Value = Session["user_afrowid"].ToString();
                    txt_ownerid.Text = Session["userid"].ToString();
                }

            }

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : loadOwneridDropDown :" + ex.Message);
        }
        finally
        {
            Hdd = null;
            BC = null;
            dt = null;
        }


    }

    private void setOwnerValues(string pownerid)
    {
        if (Request.QueryString["PK"] == null)
        {
            //ddownerid.SelectedValue = Session["user_afrowid"].ToString();
            ownerid.Value = Session["user_afrowid"].ToString();
            txt_ownerid.Text = Session["userid"].ToString();
        }
        else
        {
            //ddownerid.SelectedValue = ownerid;
            ownerid.Value = pownerid;
            LoadEditPage LEP = new LoadEditPage();
            txt_ownerid.Text = LEP.GetUserIDFromAfrowid(pownerid);
            LEP = null;
            if (Request.QueryString["CPY"] != null)
            {
                //ddownerid.SelectedValue = Session["user_afrowid"].ToString();
                ownerid.Value = Session["user_afrowid"].ToString();
                txt_ownerid.Text = Session["userid"].ToString();
            }
        }
    }


    private bool validateOwnerid()
    {
        bool status = false;
        HDDatabase HDD = new HDDatabase();
        BindControl BC = new BindControl();

        DataSet dsBind = new DataSet();
        string sql = BC.GetBindSql("f496930dfe0b690f");
        dsBind = HDD.GetDataset(sql);
        if (dsBind != null)
        {
            if (dsBind.Tables.Count > 0)
            {
                if (dsBind.Tables[0].Rows.Count > 0)
                {
                    DataRow[] drrbind = dsBind.Tables[0].Select("fld = '" + txt_ownerid.Text.Trim().Replace("'", "''") + "'");

                    if (txt_ownerid.Text.Trim() != "")
                    {
                        if (drrbind.Length > 0)
                        {
                            ownerid.Value = drrbind[0]["val"].ToString();
                            status = true;
                        }
                    }
                    else
                    {
                        ownerid.Value = "";
                        status = true;
                    }

                }
                else
                {
                    ownerid.Value = "";
                    status = true;
                }
            }
        }
        if (status != true)
        {
            lbl_message.Text = wrapItAsMessage("&nbsp;<img src='Images/Error.gif' border='0'>&nbsp;Invalid data for Owner :" + (txt_ownerid.Text), true);
        }
        return status;

    }

    private string getUseraf_row_idfromUser(string userid)
    {
        string result = "";
        try
        {
            if (dsWorkflow != null)
            {
                if (dsWorkflow.Tables.Count > 0)
                {
                    if (dsWorkflow.Tables["sy_usr"] != null)
                    {
                        DataRow[] drr = dsWorkflow.Tables["sy_usr"].Select("user_id='" + userid + "'");
                        if (drr.Length > 0)
                        {
                            result = drr[0]["af_row_id"].ToString();
                        }

                    }
                }
            }
        }
        catch
        {

        }

        return result;

    }

    private string applysecurity(string sql)
    {

        try
        {
            SecurityFilter objSec = new SecurityFilter();
            string sAFAdmin = objSec.QueryForAFAdmin();
            string sCustodianFilter = objSec.QueryForCustodianFilter();
            if (sCustodianFilter.Trim() != "")
                if (!sCustodianFilter.StartsWith("or"))
                {
                    sAFAdmin += " and " + sCustodianFilter;
                }
                else
                {
                    //if (QuickSearchSQL.Trim() == "")  // if no search exists show all no owner records
                    //{
                    sAFAdmin = "(" + sAFAdmin + " " + sCustodianFilter + ") ";
                    //sAFAdmin += " " + sCustodianFilter;
                    // }
                }

            if (sql.Contains("order by"))
            {
                if (sAFAdmin.Trim() != "")
                {
                    sql = sql.Replace("order by", "where " + sAFAdmin + " order by");
                }
            }
            else
            {
                if (sAFAdmin.Trim() != "")
                {
                    sql = sql + " where " + sAFAdmin;
                }
            }


        }
        catch
        {

        }
        return sql;
    }
    private void CheckForChangeOwner()  // Added by srivatsan to Check if user can change owner
    {
        try
        {
            security sec = new security();
            bool status = false;
            status = sec.getRightsForMRUObjects(HttpContext.Current.Request.QueryString["pgs_id"].ToString(), "change_owner");
            if (status == false)
            {

                txt_ownerid.Enabled = false;

            }
            else
            {
                PageCommonFunctions PCF = new PageCommonFunctions();
                PCF.AddSearchLink(ref tdownerid, "owner_id", "ownerid", "txt_ownerid", "f496930dfe0b690f");
                PCF = null;
            }

            sec = null;
        }
        catch
        {

        }
    }


}
